import { MultiViewContainerSchema } from '../schema/schema';
import { OperateUtils } from '../../../../utils/operate.utils';
import FdContainerBaseComponent from '../../common/containerBase/containerBase';
import { ElementPropertyConfig } from '@farris/ide-property-panel';
import { MultiViewContainerProp } from '../property/property-config';
import { FormPropertyChangeObject } from '../../../../entity/property-change-entity';
import { MultiViewUpdateViewChangeService } from '../property/services/update-view-change.service';
import { RowNode, TreeNode } from '@farris/ui-treetable';
import { MultiViewContainerContextMenuManager } from '../context-menu/context-menu.manager';
import { ControlTreeNode } from '@farris/designer-devkit';
import { ComponentSchema } from '@farris/designer-element';

export default class FdMultiViewContainerComponent extends FdContainerBaseComponent {
    // view-container-item所有项合集
    viewContainerItems = [];
    // currentItem当前项
    currentItemType;
    //
    // 标识当前的点击按钮
    get viewItemKey(): string {
        return `viewItem-${this.key}`;
    }

    /** 可视化区域顶层Form节点 */
    private formParent = null;

    constructor(component: any, options: any) {
        super(component, options);
    }

    getStyles(): string {
        return '  display: flex;flex: 1;flex-direction: column; ';

    }
    /**
     * 为了保证控件只能拖拽到MultiViewItem中，去除多视图容器的padding配置
     */
    // getClassName(): string {
    //     const className = super.getClassName();
    //     return className + ' p-0';
    // }

    getDefaultSchema(): any {

        return MultiViewContainerSchema;
    }

    getComponentAttributes() {
        return {
            viewchange: this.component.viewGroupIdentify
        };
    }

    getTemplateName(): string {
        return 'MultiViewContainer';
    }

    // 初始化
    init(): void {
        this.components = [];

        this.currentItemType = this.component.currentTypeInDesignerView || this.component.defaultType;
        if (!this.currentItemType && this.component.contents.length > 0) {
            this.currentItemType = this.component.contents[0]['id'];
        }
        this.viewContainerItems = [];
        this.component.contents.forEach((viewContainerItem, index) => {
            this.viewContainerItems[index] = [];
            viewContainerItem.contents = viewContainerItem.contents || [];
            viewContainerItem.contents.forEach((comp) => {
                // 创建Items下面的子组件
                const itemInnerCmp: any = this.createComponent(comp, this.options, null);
                this.viewContainerItems[index].push(itemInnerCmp);
            });
        });
    }

    render(): any {
        return super.render(this.renderTemplate('MultiViewContainer', {
            viewContainerItems: this.viewContainerItems.map(viewContainerItem => this.renderComponents(viewContainerItem)),
            nestedKey: this.nestedKey,
            currentItemType: this.currentItemType,
            viewItemKey: this.viewItemKey
        }));
    }
    attach(element: any): any {
        this.loadRefs(element, {
            [this.viewItemKey]: 'multiple',
        });

        const superAttach: any = super.attach(element);

        // 加载子组件
        this.refs[this.viewItemKey].forEach((tab, index) => {
            this.attachComponents(tab, this.viewContainerItems[index], this.component.contents[index].contents);
        });

        this.setPositionOfSelectedComponentBtnGroup();
        return superAttach;
    }
    /**
     * 组装属性面板配置数据
     */
    getPropertyConfig(): ElementPropertyConfig[] {
        const serviceHost = this.options.designerHost;
        const prop: MultiViewContainerProp = new MultiViewContainerProp(serviceHost, this.viewModelId, this.componentId);
        const propertyConfig: ElementPropertyConfig[] = prop.getPropConfig(this.component);
        return propertyConfig;
    }

    onPropertyChanged(changeObject: FormPropertyChangeObject, propertyIDs: string[]): void {
        super.onPropertyChanged(changeObject);

        if (changeObject.propertyID === 'contents') {
            this.updateViewChangeButtons(changeObject.propertyValue);
        }
    }

    /**
     * 视图变更后，更新对应的viewChange图标按钮组件
     * @param latestViews 变更后的视图组
     * （页头有header容器和header组件两种可能）
     */
    private updateViewChangeButtons(latestViews: any[]) {
        const parentContainer = this.parent;
        const serviceHost = this.options.designerHost;

        const domSerivice = serviceHost.getService('DomService');
        const updateViewChangeService = new MultiViewUpdateViewChangeService();
        updateViewChangeService.updateViewChangeButtons(latestViews, this.component.viewChangeBar, parentContainer, domSerivice, this.component.id);
    }

    /**
     * 更新当前显示视图
     */
    updateCurrentViewItem(selectedViewItemId: string) {
        const selectedItem = this.component.contents.find(item => item.id === selectedViewItemId);
        if (selectedItem) {
            this.currentItemType = selectedViewItemId;

            // 在DOM结构中记录当前显示视图id，用于在设计器中保持某视图的选中状态。不用于运行时
            this.component.currentTypeInDesignerView = selectedViewItemId;
            this.redraw();
        }
    }

    /**
     * 组装右键菜单
     * @param rowNode 组件在控件树上对应的行数据
     */
    resolveContextMenuConfig(rowNode: RowNode, parentRowNode: RowNode) {
        const menuManager = new MultiViewContainerContextMenuManager(this, rowNode, parentRowNode);
        return menuManager.setContextMenuConfig();
    }

    /**
     * 由外部触发组件内部的点击事件：用于在控件树中点击视图项时切换画布中的视图
     * @param treeNode 树节点
     */
    triggerComponentInsideClick(treeNode: TreeNode) {
        this.clickViewItemInControlTree(treeNode);
    }

    /**
     * 在控件树上点击某一视图项时，触发视图切换按钮的切换事件，从而达到更新当前显示视图的目的
     * @param rowNode 控件树上点击的某视图项行数据
     */
    clickViewItemInControlTree(viewItemTreeNode: TreeNode) {

        const activeItemId = viewItemTreeNode.id;
        // 更新多视图选中节点
        this.updateCurrentViewItem(activeItemId);

        // 视图按钮在section或tabPage上（子表启用多视图的场景）
        const parentTreeNode = viewItemTreeNode.parent.parent as ControlTreeNode;
        const parentContainer = parentTreeNode.rawElement;
        if (parentContainer && parentContainer.multiViews && parentContainer.views) {

            this.clickViewChangeBarInCollection(parentContainer, activeItemId);
        }
        // 视图按钮在header上（主表启用多视图的场景）
        if (this.component.viewChangeBar) {
            this.clickViewChangeBarInHeader(activeItemId);
        }

    }

    /**
     * 触发header上的viewChange click事件（此处有两种场景：ViewChange是独立的组件，或者ViewChange依附于Header组件。暂时只支持第一种）
     * @param activeItemId 当前要显示的视图id
     */
    private clickViewChangeBarInHeader(activeItemId: string) {
        const pathArray = this.component.viewChangeBar.split('.');
        const viewChangeBarId = pathArray[pathArray.length - 1];

        // 更新viewChange 按钮
        this.findFormParent();
        const viewChangeBtnEle = this.formParent.querySelectorAll('.farris-component-ViewChange[viewchange=' + this.component.viewGroupIdentify + ']');
        if (!viewChangeBtnEle || !viewChangeBtnEle.length) {
            return;
        }
        const viewChangeBtnInstance = viewChangeBtnEle[0].componentInstance;
        if (!viewChangeBtnInstance || viewChangeBtnInstance.id !== viewChangeBarId || !viewChangeBtnInstance.initActiveItem) {
            return;
        }
        viewChangeBtnInstance.initActiveItem(activeItemId);
        viewChangeBtnInstance.redraw();
    }

    /**
     * 触发Section和TabPage上的viewChange click 事件
     * @param parentContainer 视图的父容器ID
     * @param activeItemId  当前要显示的视图id
     */
    private clickViewChangeBarInCollection(parentContainer: ComponentSchema, activeItemId: string) {

        // 更新父级容器上的ViewChange图标组件
        if (!parentContainer) {
            return;
        }
        // 若是收折后的控件树触发的操作，那么parentContainer可能不是真是的DOM节点，需要重新查找DOM节点\
        const domService = this.options.designerHost.getService('DomService');
        const rootDom = domService.getComponentById(this.componentId);
        const parentContainerInDom = domService.selectNode(rootDom, item => item.id === parentContainer.id);

        parentContainerInDom.views.currentTypeInDesignerView = activeItemId;

        this.parent.redraw();
    }
    /**
     * 查找form父元素
     */
    private findFormParent() {
        if (this.formParent) {
            return;
        }
        this.formParent = OperateUtils.getFormParent(this.element);
    }

    checkCanDeleteComponent(): boolean {
        return false;
    }

    checkCanMoveComponent(): boolean {
        return false;
    }

}
